﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System.Text;
using System.Data;
using System.IO;
using System.Collections;
using Newtonsoft.Json;

namespace LeSoft.Application.Web.Areas.ResourceManage.Controllers
{
    public class RS_DeviceController : MvcControllerBase
    {

        //
        // GET: /ResourceManage/RS_Device/
        private DeviceBLL deviceBLL = new DeviceBLL();
        private DeviceRepairBLL RepairBLL = new DeviceRepairBLL();
        private DeviceTypeBLL deviceTypeBLL = new DeviceTypeBLL();
        private PollingBLL pollingBLL = new PollingBLL();
        private PollingResultBLL pollingResultBLL = new PollingResultBLL();
        private WeekPlanBLL weekPlanBLL = new WeekPlanBLL();
        private WeekBillBLL weekBillBLL = new WeekBillBLL();
        private static HttpFileCollection hfc;
        private static ArrayList hpf;
        #region 视图

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Detail()
        {
            ViewBag.Type = new DataItemDetailBLL().GetEntity("ItemName", "设备巡检", "ItemId", "PollingType").ItemDetailId;
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult DevicePartDetail()//零部件更换
        {
            return View();
        }

        //[HttpGet]
        //[HandlerAuthorize(PermissionMode.Enforce)]
        //public ActionResult DevicePollingIndex()
        //{
        //    return View();
        //}
        //[HttpGet]
        //[HandlerAuthorize(PermissionMode.Enforce)]
        //public ActionResult DevicePollingDetail()
        //{
        //    return View();
        //}


        //[HttpGet]
        //[HandlerAuthorize(PermissionMode.Enforce)]
        //public ActionResult PollingIndex()
        //{
        //    return View();
        //}
        //[HttpGet]
        //[HandlerAuthorize(PermissionMode.Enforce)]
        //public ActionResult PollingForm()
        //{
        //    return View();
        //}
        //[HttpGet]
        //[HandlerAuthorize(PermissionMode.Enforce)]
        //public ActionResult AddDatailForm()  // 内容添加
        //{
        //    return View();
        //}
        //[HttpGet]
        //[HandlerAuthorize(PermissionMode.Enforce)]
        //public ActionResult ContentDatailForm()  // 内容添加
        //{
        //    return View();
        //}
        //[HttpGet]
        //[HandlerAuthorize(PermissionMode.Enforce)]
        //public ActionResult PollingMainIndex()  //巡检看板
        //{
        //    return View();
        //}
        //[HttpGet]
        //[HandlerAuthorize(PermissionMode.Enforce)]
        //public ActionResult PlayVideoForm() //附件视频
        //{
        //    return View();
        //}
        #endregion

        #region 查询数据
        public ActionResult GetListJson(string SearchKeyWord, string TypeId = "", string PStructId = "")
        {
            var data = deviceBLL.GetList(SearchKeyWord, TypeId, PStructId).OrderBy(t => t.CreateDate);
            StringBuilder _Html = new StringBuilder();
            var index = 1;
            foreach (var item in data)
            {
                _Html.Append("<tr><td>" + index + "</td><td class='client-avatar'><img alt='image' src='/Content/images/filetype/apk.png'></td><td>" + item.Code + "</td><td>" + item.Name + "</td>");
                if (item.State == 1)
                    _Html.Append("<td><span class='label label-primary'>正常运行</span></td>");
                else
                    _Html.Append("<td><span class='label label-danger'>故障停机</span></td>");
                _Html.Append("<td>" + item.ModelNo + "</td><td>" + item.FactoryNo + "</td>");
                _Html.Append("<td><button type='button' class='btn btn-sm btn-warning' onclick='btn_add(\"" + item.Id + "\")'><i class='fa fa-pencil'></i> 编辑</button><button type='button' class='btn btn-sm btn-danger' onclick='btn_delete(\"" + item.Id + "\")'><i class='fa fa-trash-o'></i> 删除</button></td>");
                index++;
            }
            var model = data.OrderByDescending(t => t.ModifyDate).FirstOrDefault();
            var obj = new { Html = _Html.ToString(), ModifyDate = model == null ? null : model.ModifyDate != null ? model.ModifyDate : model.CreateDate, Count = data.Count() };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 设备列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="queryJson">查询参数</param>
        /// <returns>返回分页列表Json</returns>
        [HttpGet]
        public ActionResult GetPageListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var queryParam = queryJson.ToJObject();
            if (!string.IsNullOrEmpty(queryJson))
            {
                if (!queryParam["OrganizeId"].IsEmpty())
                {
                    string OrganizeId = new OrganizeCache().GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                    queryParam["OrganizeId"] = OrganizeId;
                }
                if (!queryParam["TypeId"].IsEmpty())
                {
                    string TypeId = queryParam["TypeId"].ToString();
                    var dataType = deviceTypeBLL.GetList().Where(t => t.ParentId == TypeId);
                    foreach (var item in dataType)
                    {
                        TypeId += "," + item.Id;
                    }
                    queryParam["TypeId"] = TypeId;
                }
                queryJson = queryParam.ToJson();
            }
            var data = deviceBLL.GetPageList(pagination, queryJson);
            foreach (var item in data)
            {
                item.Type = new DeviceTypeBLL().GetEntity(item.Type) == null ? "--" : new DeviceTypeBLL().GetEntity(item.Type).Name;
                var pstr = new PStructBLL().GetEntity(item.PStructId);
                item.PStructId = pstr != null ? pstr.AllName : "";
            }

            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        /// <summary>
        /// 实体 
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns>返回对象Json</returns>
        [HttpGet]
        public ActionResult GetFormJson(string keyValue, string ItemId)
        {
            var data = deviceBLL.GetEntity(keyValue);
            //data.Brand = GetName(3, ItemId);
            return Content(data.ToJson());
        }




        public ActionResult GetDeviceTypeTreeJson()
        {
            var data = new DeviceTypeBLL().GetList().ToList();
            var treeList = new List<TreeEntity>();
            foreach (DeviceTypeEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) != 0 || item.ParentId == "0" ? true : false;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Code;
                tree.parentId = item.ParentId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.title = hasChildren == false ? "0" : "1";
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        public ActionResult GetDataItemCheckBoxList(string EnCode)
        {
            var data = new DataItemCache().GetDataItemList(EnCode);
            string _Html = ""; int _Count = 0;
            if (data != null)
            {
                _Count = data.Count();
                foreach (var a in data)
                {
                    _Html += " <label><input id=" + a.ItemDetailId + " type=\"checkbox\" />" + a.ItemName + " </label>";
                }
            }
            var JsonData = new
            {
                html = _Html,
                count = _Count
            };
            return Content(JsonData.ToJson());

        }

        /// <summary>
        /// 部件变更列表
        /// </summary>
        [HttpGet]
        public ActionResult GetDList(string DeviceId)
        {
            var data = deviceBLL.GetDList(DeviceId);
            return Content(data.ToJson());
        }

        ///<summary>
        ///获取保养列表
        ///</summary>
        ///<param name="queryJson"></param>
        ///<returns></returns>
        public ActionResult GetWeekList(string queryJson)
        {
            var data = weekPlanBLL.GetListJson(queryJson);
            return Content(data);
        }

        /// <summary>
        /// 获取维修列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRepairList(Pagination pagination, string queryJson)
        {
            var data = RepairBLL.GetPageList(pagination, queryJson).ToList();
            return Content(data.ToJson());
        }
        #endregion

        #region 验证数据
        /// <summary>
        /// 种类名称不能重复
        /// </summary>
        /// <param name="Name">种类名称</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExistName(string Name, string keyValue)
        {
            bool IsOk = deviceBLL.ExistName(Name, keyValue);
            return Content(IsOk.ToString());
        }
        /// <summary>
        /// 种类编号不能重复
        /// </summary>
        /// <param name="Code">种类编号</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExistCode(string Code, string keyValue)
        {
            bool IsOk = deviceBLL.ExistCode(Code, keyValue);
            return Content(IsOk.ToString());
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 保存设备表单（新增、修改）
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="deviceTypeEntity">种类实体</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, string DeviceStr, string DatasStr, string PartsStr)
        {
            DeviceEntity deviceEntity = DeviceStr.ToObject<DeviceEntity>();
            List<DeviceDatasInstanceEntity> deviceDatasInstanceList = DatasStr.ToList<DeviceDatasInstanceEntity>();
            List<DevicePartsInstanceEntity> devicePartsInstanceList = PartsStr.ToList<DevicePartsInstanceEntity>();
            deviceBLL.SaveForm(keyValue, deviceEntity, null, deviceDatasInstanceList, devicePartsInstanceList);
            string id = deviceEntity.Id;
            return Success("操作成功。", id);
        }
        /// <summary>
        /// 保存设备修改记录
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveDeviceParts(string list)
        {
            try
            {
                List<DeviceParts> devicePartsList = list.ToList<DeviceParts>();
                deviceBLL.SaveDeviceParts(devicePartsList);
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult RemoveForm(string keyValue)
        {
            deviceBLL.RemoveForm(keyValue);
            return Success("删除成功。");
        }
        #endregion



        /// <summary>
        /// 获取设备种类+设备树
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDeviceTypeTreeToJson()
        {
            var data = new DeviceTypeBLL().GetList().ToList();
            var query = deviceBLL.GetList().ToList();
            var treeList = new List<TreeEntity>();

            foreach (DeviceTypeEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = true; //data.Count(t => t.Id == item.ParentId) == 0 ? false :true
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.parentId = item.ParentId == null ? "All" : item.ParentId;
                tree.isexpand = true;
                tree.img = "fa fa-folder-o";
                tree.complete = true;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            foreach (DeviceEntity item in query)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = false; //data.Count(t => t.Id == item.ParentId) == 0 ? false :true
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.parentId = item.Type;
                tree.isexpand = true;
                tree.complete = true;
                tree.img = "fa fa-cog";
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }









        public ActionResult GetDeviceList(string queryjson)
        {
            var data = new DeviceBLL().GetList().ToList();
            var queryParam = queryjson.ToJObject();
            string DeviceLevel = queryParam["Level"].ToString();
            string ProjectType = queryParam["Project"].ToString();
            string DeviceTypeId = queryParam["Type"].ToString();
            if (!queryParam["OrganizeId"].IsEmpty())
            {
                var OrganizeId = new OrganizeCache().GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                data = data.Where(t => OrganizeId.Contains(t.OrganizeId)).ToList();
            }
            data = data.Where(e => DeviceLevel.Contains(e.Level) && DeviceTypeId.Contains(e.Type)).ToList();
            List<object> objlist = new List<object>();
            foreach (var item in data)
            {
                var TypeName = new DeviceTypeBLL().GetEntity(item.Type).IsEmpty() ? "" : new DeviceTypeBLL().GetEntity(item.Type).Name;
                var dd = new DataItemCache().GetDataItemList("DeviceLevel").FirstOrDefault(e => e.ItemDetailId == item.Level);
                var Level = dd.IsEmpty() ? "" : dd.ItemName;
                var organize = new OrganizeCache().GetEntity(item.OrganizeId);
                if (organize.IsEmpty() || !ProjectType.Contains(organize.BusinessScope))
                {
                    continue;
                }
                objlist.Add(new { Id = item.Id, TypeId = item.Type, Type = TypeName, LevelValue = item.Level, Level = Level, Code = item.Code, Name = item.Name, OrganizeId = item.OrganizeId, ProjectType = organize.BusinessScope });
            }
            return Content(objlist.ToJson());
        }

        public ActionResult GetDeviceCheckBoxListJson()
        {
            var data = deviceBLL.GetList().ToList();
            var treeList = new List<TreeEntity>();
            foreach (DeviceEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = false;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Code;
                tree.parentId = "0";
                tree.showcheck = true;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        public ActionResult GetDeviceLeveCheckBox(string keyValue)
        {
            string html = "";
            var data = new DataItemDetailBLL().GetList("DeviceLevel").ToList();
            foreach (var item in data)
            {
                html += "<label><input id=\"" + item.ItemDetailId + "\" name='checkLevel' value=\"" + item.ItemDetailId + "\"type='checkbox'";
                html += keyValue.Contains(item.ItemDetailId) ? "checked" : "";
                html += "/> " + item.ItemName + " </label>";
            }
            return Content(html);
        }
        public ActionResult GetProjectTypeCheckBox(string keyValue)
        {
            string html1 = "";
            var data1 = new DataItemDetailBLL().GetList("ProjectType").ToList();
            foreach (var item in data1)
            {
                html1 += "<label><input id=\"" + item.ItemDetailId + "\" name='checkType' value=\"" + item.ItemDetailId + "\"type='checkbox'";
                html1 += keyValue.Contains(item.ItemDetailId) ? "checked" : "";
                html1 += "/> " + item.ItemName + " </label>";
            }
            return Content(html1);
        }
        public ActionResult GetCheckBoxTreeJson(string DeviceTypeId)
        {
            var data = new DeviceTypeBLL().GetList().ToList();
            var treeList = new List<TreeEntity>();
            treeList.Add(new TreeEntity() { id = "All", value = "All", text = "所有设备", parentId = "0", showcheck = true, checkstate = 0, hasChildren = true, isexpand = true, complete = true });
            foreach (DeviceTypeEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Code;
                tree.parentId = item.ParentId == "0" ? "All" : item.ParentId;
                tree.showcheck = true;
                tree.isexpand = true;
                tree.checkstate = DeviceTypeId.Contains(item.Id) ? 1 : 0;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.title = hasChildren == false ? "0" : "1";
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        public ActionResult GetCheckBoxPollingContentTreeJson(string keyValue)
        {
            var data = pollingBLL.GetContentList().ToList();
            List<TreeEntity> treeList = new List<TreeEntity>();
            if (!keyValue.IsEmpty())
            {
                foreach (PollingContentEntity item in data)
                {
                    TreeEntity tree = new TreeEntity();
                    bool hasChildren = false;
                    tree.id = item.Id;
                    tree.text = item.Name;
                    tree.value = item.Id;
                    tree.parentId = "0";
                    tree.showcheck = true;
                    tree.checkstate = keyValue.Contains(item.Id) ? 1 : 0;
                    tree.isexpand = true;
                    tree.complete = true;
                    tree.hasChildren = hasChildren;
                    tree.title = hasChildren == false ? "0" : "1";
                    treeList.Add(tree);
                }
                return Content(treeList.TreeToJson());
            }

            foreach (PollingContentEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = false;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.parentId = "0";
                tree.showcheck = true;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.title = hasChildren == false ? "0" : "1";
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }



        public ActionResult GetPartssInstanceList(string DeviceId)
        {
            var data = deviceTypeBLL.GetPartssInstanceList(DeviceId).Join(deviceTypeBLL.GetPartsList("{}"), x => x.DevicePartsId, t => t.Id, (x, t) => new
            {
                t.ModelNo,
                t.Description,
                t.Factory,
                t.Name,
                t.Price,
                x.Verdors,
                x.UnitPrice,
                x.Total,
                x.OpreateMemo,
                x.Num,
                x.ModifyDate,
                x.Id,
                x.EndDate,
                x.DevicePartsId,
                x.DeviceId,
                x.CreateDate,
                x.BeginDate
            });
            return Content(data.ToJson());
        }






        public ActionResult GetOrganizeTree()
        {
            var data = new OrganizeCache().GetList().ToList();
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = new OrganizeCache().GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                data = data.Where(t => organizeids.Contains(t.OrganizeId)).ToList();
            }
            var treeList = new List<TreeEntity>();
            foreach (OrganizeEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.OrganizeId) == 0 ? false : true;
                tree.id = item.OrganizeId;
                tree.text = item.FullName;
                tree.value = item.OrganizeId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.img = "fa fa-sitemap";
                if (!OperatorProvider.Provider.Current().IsSystem) tree.parentId = item.OrganizeId == OperatorProvider.Provider.Current().CompanyId ? "0" : item.ParentId;
                else tree.parentId = item.ParentId;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        [HttpPost]
        public ActionResult GetDeviceLevelList()
        {
            var data = new DataItemDetailBLL().GetList("DeviceLevel").ToList();

            return Content(data.ToJson());
        }
        //GetProjectTypeList
        public ActionResult GetProjectTypeList()
        {
            var data = new DataItemDetailBLL().GetList("ProjectType").ToList();

            return Content(data.ToJson());
        }
        public ActionResult GetPollingItemList(string queryJson)
        {

            var query = deviceBLL.GetRelationDeviceItemList(1, null).ToList();

            var queryParam = queryJson.ToJObject();
            if (!queryParam["OrganizeId"].IsEmpty())
            {
                query = query.Where(e => e.OrganizeId == queryParam["OrganizeId"].ToString()).ToList();
            }
            if (!queryParam["Level"].IsEmpty())
            {
                query = query.Where(e => e.DeviceLevel == queryParam["Level"].ToString()).ToList();
            }
            if (!queryParam["DeviceId"].IsEmpty())
            {
                var lst1 = new DeviceTypeBLL().GetEntity(queryParam["DeviceId"].ToString());
                var lst2 = deviceBLL.GetEntity(queryParam["DeviceId"].ToString());
                if (!lst1.IsEmpty())
                {
                    var s = new DeviceTypeBLL().GetList().ToList();
                    s = s.Where(e => e.ParentId == lst1.Id).ToList();
                    if (s.Count() != 0)
                    {
                        List<RelationDeviceItemEntity> lstRDI = new List<RelationDeviceItemEntity>();
                        foreach (var item in s)
                        {
                            List<RelationDeviceItemEntity> lst = query.Where(e => e.DeviceTypeId == item.Id).ToList();
                            foreach (var item1 in lst)
                            {
                                lstRDI.Add(item1);
                            }
                        }
                        query = lstRDI;
                    }
                    else
                    {
                        query = query.Where(e => e.DeviceTypeId == queryParam["DeviceId"].ToString()).ToList();
                    }

                }
                if (!lst2.IsEmpty())
                {
                    query = query.Where(e => e.DeviceId == queryParam["DeviceId"].ToString()).ToList();
                }
            }
            if (!queryParam["ProjectType"].IsEmpty())
            {
                query = query.Where(e => e.ProjectType == queryParam["ProjectType"].ToString()).ToList();
            }
            query = query.Where((x, i) => query.FindIndex(z => z.ItemId == x.ItemId) == i).ToList();
            var data = new List<PollingItemEntity>();
            foreach (var item in query)
            {
                data.Add(pollingBLL.GetItemEntity(item.ItemId));
            }
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                var condition = queryParam["condition"].ToString();
                var keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "Name":
                        data = data.Where(t => t.Name.Contains(keyword)).ToList();
                        break;
                    case "Code":
                        data = data.Where(t => t.Code.Contains(keyword)).ToList();
                        break;
                    default:
                        break;
                }
            }
            var datalist = from s in data
                           select new
                           {
                               s.Id,
                               s.Code,
                               s.Name,
                               s.Unit,
                               s.UnitNum,
                               s.Frenquency,
                               InstallType = GetName(1, s.Id),
                               Level = GetName(2, s.Id),
                               BllTypeId = GetName(3, s.Id)
                           };
            return Content(datalist.ToJson());
            //   return Content(data.ToJson());
        }

        public ActionResult GetPollingItemEntity(string keyValue)
        {
            var lst1 = pollingBLL.GetItemEntity(keyValue);
            var query = pollingBLL.GetRelationContentList("7cf6de3d-5d1e-4123-8971-3e7efd607219", keyValue);//8F09CCF7-5CD6-44C7-8C61-0BF24757FCC2
            var lst = deviceBLL.GetRelationDeviceItemList(1, null);
            lst = lst.Where(e => e.ItemId == lst1.Id).ToList();
            string str = "";
            string DeviceLevel = "";
            string ProjectType = "";
            string DeviceTypeId = "";
            if (query.Count() != 0)
            {
                foreach (PollingRelationICEntity item in query)
                {
                    str += item.ContentId + ",";
                }
                str = str.Substring(0, str.Length - 1);
            }
            if (lst.Count() != 0)
            {
                foreach (RelationDeviceItemEntity item in lst)
                {
                    if (!DeviceLevel.Contains(item.DeviceLevel))
                    {
                        DeviceLevel += item.DeviceLevel + ",";
                    }
                    if (!ProjectType.Contains(item.ProjectType))
                    {
                        ProjectType += item.ProjectType + ",";
                    }
                    if (!DeviceTypeId.Contains(item.DeviceTypeId))
                    {
                        DeviceTypeId += item.DeviceTypeId + ",";
                    }
                }
                DeviceLevel = DeviceLevel.Substring(0, DeviceLevel.Length - 1);
                ProjectType = ProjectType.Substring(0, ProjectType.Length - 1);
                DeviceTypeId = DeviceTypeId.Substring(0, DeviceTypeId.Length - 1);
            }


            var data = new
            {
                data1 = lst1,
                data2 = str,
                data3 = DeviceLevel,
                data4 = ProjectType,
                data5 = DeviceTypeId
            };
            return Content(data.ToJson());
        }


        public ActionResult GetDeviceInfolist(string keyValue, string condition, string keyword, string TypeId)
        {
            var data = deviceBLL.GetList();
            data = data.Where(e => e.OrganizeId == keyValue);
            if (!string.IsNullOrEmpty(condition) && !string.IsNullOrEmpty(keyword))
            {
                switch (condition)
                {
                    case "Code": data = data.Where(e => e.Code.Contains(keyword)); break;
                    case "Name": data = data.Where(e => e.Name.Contains(keyword)); break;
                    default:
                        break;
                }
            }
            if (!string.IsNullOrEmpty(TypeId))
            {
                var dataType = deviceTypeBLL.GetList().Where(t => t.ParentId == TypeId);
                foreach (var item in dataType)
                {
                    TypeId += "," + item.Id;
                }
                data = data.Where(e => TypeId.Contains(e.Type));
            }
            var TypeList = deviceTypeBLL.GetList();
            var PStructList = new PStructBLL().GetList();
            var datalist = data.GroupJoin(TypeList, t => t.Type, y => y.Id, (x, y) => new { x.Id, x.Name, x.Code, x.PStructId, x.ModelNo, x.State, x.Description, Type = y.FirstOrDefault() != null ? y.FirstOrDefault().Name : "---" }).GroupJoin(PStructList, x => x.PStructId, y => y.Id, (x, y) => new { x.Id, x.Name, x.Code, x.ModelNo, x.State, x.Description, x.Type, PStructId = y.FirstOrDefault() != null ? y.FirstOrDefault().AllName : "---" });
            //foreach (DeviceEntity item in data)
            //{
            //    var query = TypeList.FirstOrDefault(t => t.Id == item.Type);
            //    item.Type = query == null ? "---" : query.Name;
            //    var PStruct = PStructList.FirstOrDefault(t => t.Id == item.PStructId);
            //    item.PStructId = PStruct == null ? "---" : PStruct.AllName;
            //}
            return Content(datalist.ToJson());
        }


        public ActionResult GetRepairInfoListById(string keyValue)
        {
            var data = RepairBLL.GetList().ToList();
            // data = data.Where(e => e.DeviceId == keyValue).ToList();
            return Content(data.ToJson());
        }
        public ActionResult GetPollingContentListToJson(string keyValue)
        {
            if (!keyValue.IsEmpty())
            {
                string[] str = keyValue.Split(',');
                List<PollingContentEntity> lst = new List<PollingContentEntity>();
                foreach (var item in str)
                {
                    var data = pollingBLL.GetContentEntity(item);
                    lst.Add(data);
                }
                return Content(lst.ToJson());
            }
            else
            {
                return null;
            }

        }
        public ActionResult GetPollingContentFormJson(string keyValue)
        {

            var data = pollingBLL.GetContentEntity(keyValue);
            return Content(data.ToJson());
        }


        public ActionResult SavePollingContentForm(string keyValue, PollingContentEntity entity)
        {
            try
            {
                pollingBLL.SaveCForm(keyValue, entity);
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }





        [HttpPost]
        public ActionResult SavePollingForm(string keyValue, PollingItemEntity entity, string List, string DeviceLevel, string ProjectType, string DeviceTypeId)
        {
            entity.TypeName = "设备巡检";
            List<RelationDeviceItemEntity> list = new List<RelationDeviceItemEntity>();
            string[] str = List.Split(',');
            string[] level = DeviceLevel.Split(',');
            string[] projecttype = ProjectType.Split(',');
            string[] devicetypeid = DeviceTypeId.Split(',');
            for (int i = 0; i < level.Length; i++)
            {
                for (int j = 0; j < projecttype.Length; j++)
                {
                    for (int k = 0; k < devicetypeid.Length; k++)
                    {
                        list.Add(new RelationDeviceItemEntity()
                        {
                            ItemTag = 1,
                            ItemType = new DataItemDetailBLL().GetList("PollingType") == null ? "" : new DataItemDetailBLL().GetList("PollingType").FirstOrDefault(e => e.ItemCode == "SB_XJ").ItemDetailId,
                            OrganizeId = entity.OrganizeId,
                            DeviceLevel = level[i],
                            ProjectType = projecttype[j],
                            DeviceTypeId = devicetypeid[k]
                        });
                    }
                }
            }
            List<PollingContentEntity> lst = new List<PollingContentEntity>();
            foreach (var item in str)
            {
                var data = pollingBLL.GetContentEntity(item);
                lst.Add(data);
            }
            try
            {
                pollingBLL.SaveIForm(keyValue, entity, list, lst);
                return Success("操作成功！");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }


        public ActionResult RemovePollingContentForm(string keyValue)
        {
            try
            {
                pollingBLL.RemoveCForm(keyValue);
                return Success("删除成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

        public ActionResult RemovePollingItemForm(string keyValue)
        {
            try
            {
                pollingBLL.RemoveIForm(keyValue);
                return Success("操作成功！");
            }
            catch (Exception e)
            {

                return Error(e.Message);
            }
        }



        public ActionResult UploadFile()
        {
            hfc = System.Web.HttpContext.Current.Request.Files;
            return Success("操作成功。");
        }
        public ActionResult DeleteFile(string FileName)
        {
            string[] ss = FileName.Split(',');
            if (ss.Length > 0)
            {
                for (int j = 0; j < ss.Length; j++)
                {
                    hpf.Add(ss[j]);
                }
            }
            return Success("操作成功。");
        }



        #region 项目巡检看板

        public ActionResult GetDevicePollingTreeTojson()
        {
            var data = pollingBLL.GetItemList("", "", "7cf6de3d-5d1e-4123-8971-3e7efd607219").ToList();
            List<TreeEntity> lst = new List<TreeEntity>();
            foreach (PollingItemEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = false; //data.Count(t => t.Id == item.ParentId) == 0 ? false :true
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.parentId = "0";  //item.ParentId == null ? "All" : item.ParentId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                lst.Add(tree);
            }
            return Content(lst.TreeToJson());
        }


        public ActionResult GetDevicePollingColMsJson(string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            int type = Convert.ToInt32(queryParam["type"]);
            string organizeid = queryParam["organizeid"].ToString();
            string PollingId = queryParam["PollingId"].ToString();
            string DeviceId = queryParam["DeviceId"].ToString();
            DateTime EndTime = Convert.ToDateTime(queryParam["EndTime"]);
            DateTime StartTime = Convert.ToDateTime(queryParam["StartTime"]);
            IList<object> ColMs = new List<object>();
            int intervalDate = 0;
            var query = pollingBLL.GetItemList("", "", "7cf6de3d-5d1e-4123-8971-3e7efd607219").ToList();

            foreach (PollingItemEntity item in query)
            {
                switch (item.Unit)
                {
                    case "0": item.Frenquency = item.UnitNum + "天" + item.Frenquency + "次";
                        break;
                    case "1": item.Frenquency = item.UnitNum + "周" + item.Frenquency + "次";
                        break;
                    case "2": item.Frenquency = item.UnitNum + "月" + item.Frenquency + "次";
                        break;
                    case "3": item.Frenquency = item.UnitNum + "季" + item.Frenquency + "次";
                        break;
                    case "4": item.Frenquency = item.UnitNum + "年" + item.Frenquency + "次";
                        break;
                }

            }
            var list = new PollingResultBLL().GetList().ToList();
            if (!organizeid.IsEmpty())
            {
                list = list.Where(e => e.OrganizeId == organizeid).ToList();
            }
            if (!PollingId.IsEmpty())
            {
                list = list.Where(e => e.Bcode == PollingId).ToList();
            }
            if (!DeviceId.IsEmpty())
            {
                var lst1 = new DeviceTypeBLL().GetEntity(DeviceId);
                var lst2 = deviceBLL.GetEntity(DeviceId);
                if (!lst1.IsEmpty())
                {

                    var s = deviceBLL.GetList().Where(e => e.Type == DeviceId).ToList();
                    if (s.Count() != 0)
                    {
                        List<PollingResultEntity> PRlst = new List<PollingResultEntity>();
                        foreach (var item in s)
                        {
                            List<PollingResultEntity> lst = list.Where(e => e.ObjectId == item.Id).ToList();
                            foreach (var item1 in lst)
                            {
                                PRlst.Add(item1);
                            }
                        }
                        list = PRlst;
                    }
                    else
                    {
                        list = list.Where(e => e.ObjectId == DeviceId).ToList();
                    }
                }
                if (!lst2.IsEmpty())
                {
                    list = list.Where(e => e.ObjectId == DeviceId).ToList();
                }
            }
            var datalist = query.Join(list, x => x.Id, y => y.Bcode, (x, y) => new
            {
                Id = y.Id,
                PName = x.Name,
                PId = y.Bcode,
                DName = new DeviceBLL().GetEntity(y.ObjectId) == null ? "" : new DeviceBLL().GetEntity(y.ObjectId).Name,
                PStructId = new DeviceBLL().GetEntity(y.ObjectId) == null ? "" : new PStructBLL().GetEntity(new DeviceBLL().GetEntity(y.ObjectId).PStructId).AllName,
                Frenquency = x.Frenquency,
                DId = y.ObjectId,
                Date = y.Date
            }).GroupBy(t => t.DId);

            string str = "[";
            int rows = 0, sum = 0, count = 0;
            switch (type)
            {
                case 1:
                    intervalDate = (EndTime - StartTime).Days;
                    if (datalist.Count() <= 0)
                    {
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddDays(i);
                            object colms = new object();
                            if (i == 0)
                            {
                                colms = new { label = "主键", name = "Id", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "项目主键", name = "PId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "设备主键", name = "DId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "项目名称", name = "PName", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "设备名称", name = "DName", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "安装位置", name = "PStructId", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "频次", name = "Frequency", index = "Frequency", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                            colms = new { label = date.ToString("yyyy-MM-dd") + "<br/>(" + Time.GetWeekNameOfDay(date) + ")", name = "Date" + i, width = 100, align = "center", sortable = false };
                            ColMs.Add(colms);
                            if (i == intervalDate)
                            {
                                colms = new { label = "小计", name = "Sum", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                        }
                    }
                    foreach (var item in datalist)
                    {
                        if (rows != 0)
                        {
                            str += ",";
                        }
                        str += "{\"Id\":\"" + item.Key + "\",";
                        if (item.FirstOrDefault() == null)
                        {
                            str += "\"PId\":\"\",\"DId\":\"\",\"PName\":\"\",\"DName\":\"\",\"PStructId\":\"\",\"Frequency\":\"";
                        }   //PStructId
                        else
                        {
                            var model = item.FirstOrDefault();
                            str += "\"PId\":\"" + model.PId + "\"," + "\"DId\":\"" + model.DId + "\"," + "\"PName\":\"" + model.PName + "\"" + ",\"DName\":\"" + model.DName + "\"" + ",\"PStructId\":\"" + model.PStructId + "\"" + ",\"Frequency\":\"" + model.Frenquency + "\"";
                        }
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddDays(i);
                            if (rows == 0)
                            {
                                object colms = new object();
                                if (i == 0)
                                {
                                    colms = new { label = "主键", name = "Id", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "项目主键", name = "PId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "设备主键", name = "DId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "项目名称", name = "PName", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "设备名称", name = "DName", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "安装位置", name = "PStructId", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "频次", name = "Frequency", index = "Frequency", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                                colms = new { label = date.ToString("yyyy-MM-dd") + "<br/>(" + Time.GetWeekNameOfDay(date) + ")", name = "Date" + i, width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                if (i == intervalDate)
                                {
                                    colms = new { label = "小计", name = "Sum", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                            }
                            count = item.Count(t => t.Date.Value.Date == date.Date);
                            sum += count;
                            str += ",\"Date" + i + "\":" + count;
                        }
                        str += ",\"Sum\":" + sum + "}";
                        sum = 0;
                        rows++;
                    }

                    break;
                case 2:
                    intervalDate = (EndTime - StartTime).Days / 7;
                    if (datalist.Count() <= 0)
                    {
                        for (int i = 1; i <= intervalDate; i++)
                        {
                            int s = i * 7 - 7;
                            DateTime date = StartTime.AddDays(s);
                            object colms = new object();
                            if (i == 1)
                            {
                                colms = new { label = "主键", name = "Id", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "项目主键", name = "PId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "设备主键", name = "DId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "项目名称", name = "PName", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "设备名称", name = "DName", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "安装位置", name = "PStructId", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "频次", name = "Frequency", index = "Frequency", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                            colms = new { label = "第" + i + "周", width = 120, align = "center", sortable = false };
                            ColMs.Add(colms);
                            if (i == intervalDate)
                            {
                                colms = new { label = "小计", name = "Sum", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                        }
                    }
                    foreach (var item in datalist)
                    {
                        if (rows != 0)
                        {
                            str += ",";
                        }
                        str += "{\"Id\":\"" + item.Key + "\",";
                        if (item.FirstOrDefault() == null)
                        {
                            str += "\"PId\":\"\",\"DId\":\"\",\"PName\":\"\",\"DName\":\"\",\"PStructId\":\"\",\"Frequency\":\"";
                        }   //PStructId
                        else
                        {
                            var model = item.FirstOrDefault();
                            str += "\"PId\":\"" + model.PId + "\"," + "\"DId\":\"" + model.DId + "\"," + "\"PName\":\"" + model.PName + "\"" + ",\"DName\":\"" + model.DName + "\"" + ",\"PStructId\":\"" + model.PStructId + "\"" + ",\"Frequency\":\"" + model.Frenquency + "\"";
                        }
                        for (int i = 1; i <= intervalDate; i++)
                        {
                            int s = i * 7 - 7;
                            DateTime date = StartTime.AddDays(s);
                            if (rows == 0)
                            {
                                object colms = new object();
                                if (i == 1)
                                {
                                    colms = new { label = "主键", name = "Id", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "项目主键", name = "PId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "设备主键", name = "DId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "项目名称", name = "PName", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "设备名称", name = "DName", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "安装位置", name = "PStructId", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "频次", name = "Frequency", index = "Frequency", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                                colms = new { label = "第" + i + "周", name = "Date" + i, width = 120, align = "center", sortable = false };
                                ColMs.Add(colms);
                                if (i == intervalDate)
                                {
                                    colms = new { label = "小计", name = "Sum", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                            }
                            DateTime STime = date;
                            DateTime ETime = date.AddDays(7);
                            count = item.Count(t => t.Date.Value >= STime && t.Date.Value <= ETime);
                            sum += count;
                            str += ",\"Date" + i + "\":" + count;
                        }
                        str += ",\"Sum\":" + sum + "}";
                        sum = 0;
                        rows++;
                    }
                    break;
                case 3:
                    intervalDate = (EndTime.Month - StartTime.Month) + ((EndTime.Year - StartTime.Year) * 12);
                    if (datalist.Count() <= 0)
                    {
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddMonths(i);
                            object colms = new object();
                            if (i == 0)
                            {

                                colms = new { label = "主键", name = "Id", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "项目主键", name = "PId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "设备主键", name = "DId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "项目名称", name = "PName", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "设备名称", name = "DName", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "安装位置", name = "PStructId", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "频次", name = "Frequency", index = "Frequency", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                            colms = new { label = date.Year + "年" + date.Month + "月", name = "Date" + i, width = 90, align = "center", sortable = false };
                            ColMs.Add(colms);
                            if (i == intervalDate)
                            {
                                colms = new { label = "小计", name = "Sum", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }

                        }
                    }
                    foreach (var item in datalist)
                    {
                        if (rows != 0)
                        {
                            str += ",";
                        }
                        str += "{\"Id\":\"" + item.Key + "\",";
                        if (item.FirstOrDefault() == null)
                        {
                            str += "\"PId\":\"\",\"DId\":\"\",\"PName\":\"\",\"DName\":\"\",\"PStructId\":\"\",\"Frequency\":\"";
                        }   //PStructId
                        else
                        {
                            var model = item.FirstOrDefault();
                            str += "\"PId\":\"" + model.PId + "\"," + "\"DId\":\"" + model.DId + "\"," + "\"PName\":\"" + model.PName + "\"" + ",\"DName\":\"" + model.DName + "\"" + ",\"PStructId\":\"" + model.PStructId + "\"" + ",\"Frequency\":\"" + model.Frenquency + "\"";
                        }
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddMonths(i);
                            if (rows == 0)
                            {
                                object colms = new object();
                                if (i == 0)
                                {
                                    colms = new { label = "主键", name = "Id", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "项目主键", name = "PId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "设备主键", name = "DId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "项目名称", name = "PName", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "设备名称", name = "DName", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "安装位置", name = "PStructId", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "频次", name = "Frequency", index = "Frequency", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                                colms = new { label = date.Year + "年" + date.Month + "月", name = "Date" + i, width = 90, align = "center", sortable = false };
                                ColMs.Add(colms);
                                if (i == intervalDate)
                                {
                                    colms = new { label = "小计", name = "Sum", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                            }
                            count = item.Count(t => t.Date.Value.Year == date.Year && t.Date.Value.Month == date.Date.Month);
                            sum += count;
                            str += ",\"Date" + i + "\":" + count;
                        }
                        str += ",\"Sum\":" + sum + "}";
                        sum = 0;
                        rows++;
                    }
                    break;
                case 4:
                    intervalDate = (EndTime.Year - StartTime.Year);
                    if (datalist.Count() <= 0)
                    {
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddYears(i);
                            object colms = new object();
                            if (i == 0)
                            {

                                colms = new { label = "主键", name = "Id", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "项目主键", name = "PId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "设备主键", name = "DId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "项目名称", name = "PName", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "设备名称", name = "DName", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "安装位置", name = "PStructId", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "频次", name = "Frequency", index = "Frequency", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                            colms = new { label = date.Year + "年", name = "Date" + i, width = 90, align = "center", sortable = false };
                            ColMs.Add(colms);
                            if (i == intervalDate)
                            {
                                colms = new { label = "小计", name = "Sum", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }

                        }
                    }
                    foreach (var item in datalist)
                    {
                        if (rows != 0)
                        {
                            str += ",";
                        }
                        str += "{\"Id\":\"" + item.Key + "\",";
                        if (item.FirstOrDefault() == null)
                        {
                            str += "\"PId\":\"\",\"DId\":\"\",\"PName\":\"\",\"DName\":\"\",\"PStructId\":\"\",\"Frequency\":\"";
                        }   //PStructId
                        else
                        {
                            var model = item.FirstOrDefault();
                            str += "\"PId\":\"" + model.PId + "\"," + "\"DId\":\"" + model.DId + "\"," + "\"PName\":\"" + model.PName + "\"" + ",\"DName\":\"" + model.DName + "\"" + ",\"PStructId\":\"" + model.PStructId + "\"" + ",\"Frequency\":\"" + model.Frenquency + "\"";
                        }
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddYears(i);
                            if (rows == 0)
                            {
                                object colms = new object();
                                if (i == 0)
                                {
                                    colms = new { label = "主键", name = "Id", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "项目主键", name = "PId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "设备主键", name = "DId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "项目名称", name = "PName", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "设备名称", name = "DName", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "安装位置", name = "PStructId", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "频次", name = "Frequency", index = "Frequency", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                                colms = new { label = date.Year + "年", name = "Date" + i, width = 90, align = "center", sortable = false };
                                ColMs.Add(colms);
                                if (i == intervalDate)
                                {
                                    colms = new { label = "小计", name = "Sum", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                            }
                            count = item.Count(t => t.Date.Value.Year == date.Year);
                            sum += count;
                            str += ",\"Date" + i + "\":" + count;
                        }
                        str += ",\"Sum\":" + sum + "}";
                        sum = 0;
                        rows++;
                    }
                    break;

                default:
                    break;
            }
            str += "]";
            object obj = JsonConvert.DeserializeObject<object>(str);
            var coldata = new { total = rows, records = rows, rows = obj };
            var data = new
            {
                data1 = ColMs,
                data2 = coldata
            };
            return Content(data.ToJson());
        }


        //明细
        //  postData: { StartTime: StartTime, AddDate: AddDate, Id: Id, PId: PId, DId: DId, type: type },
        public ActionResult GetDevicePollingResultList(DateTime StartTime, int AddDate, string Id, string PId, string DId, int type)
        {
            DateTime EndTime = new DateTime();
            switch (type)
            {
                case 1: StartTime = StartTime.AddDays(AddDate); EndTime = StartTime.AddDays(1).AddSeconds(-1); break;
                case 2: StartTime = StartTime.AddDays(AddDate * 7); EndTime = StartTime.AddDays(7).AddSeconds(-1); break;
                case 3: StartTime = StartTime.AddMonths(AddDate); EndTime = StartTime.AddMonths(1).AddSeconds(-1); break;
                case 4: StartTime = StartTime.AddYears(AddDate); EndTime = StartTime.AddYears(1).AddSeconds(-1); break;
                default:
                    break;
            }
            var data = new PollingResultBLL().GetList(DId, PId).ToList();
            var query1 = new PollingResultBLL().GetDetailList().ToList();
            data = data.Where(e => e.Date >= StartTime && e.Date <= EndTime).ToList();
            var query = from result in data
                        select new
                        {
                            Id = query1.Where(e => e.PollingResultId == result.Id).FirstOrDefault().Id,
                            PId = PId,
                            Date = result.Date,
                            Icode = result.Icode,
                            PName = pollingBLL.GetItemEntity(PId).Name,
                            DCode = deviceBLL.GetEntity(DId).Code,
                            PStructId = new PStructBLL().GetEntity(deviceBLL.GetEntity(DId).PStructId).AllName
                        };
            return Content(query.ToJson());
        }

        public ActionResult GetPollingResultDetailList(string keyValue, string PId)
        {
            // var data = new PollingResultBLL().GetDetailList(keyValue);
            // var data2 = pollingBLL.GetRelationContentList("7cf6de3d-5d1e-4123-8971-3e7efd607219", PId).ToList();
            // List<PollingContentEntity> lst = new List<PollingContentEntity>();

            ////   Id   Type  Sort   Flag  Text  Value DefaultValue ValueType  MinValue MaxValue  IsException IsDefault 
            // //var Entity = new
            // //{
            // //    Id = "",
            // //    Type = "",
            // //    Sort = "",
            // //    Flag = "",
            // //    Text = "",
            // //    Value = "",
            // //    DefaultValue = "",
            // //    ValueType = "",
            // //    MinValue = "",
            // //    MaxValue = "",
            // //    IsException = "",
            // //    IsDefault = ""
            // //};


            // List<PCIEntity> lst1 = new List<PCIEntity>();
            // int i = 1;
            // foreach (var item in data2)
            // {
            //     var query = pollingBLL.GetContentEntity(item.ContentId);
            //     string str = query.TypeDescription;
            //     lst1 = str.ToObject<List<PCIEntity>>();
            //     string html = "<div>";

            //     foreach (PCIEntity pci in lst1)
            //     {
            //         if (pci.Type == "选择型")//选择型
            //         {
            //             //  html += "<label class=\"radio inline\" >";
            //             html += "<input type=\"radio\" style=\"margin-left:5px; \"disabled name=\"" + pci.Id + "\"id=\"optionsRadios\"";
            //             if (pci.IsDefault == "1")
            //             {
            //                 html += "checked=\"checked\"";
            //             }
            //             html += "value=" + pci.Value + " />" + pci.Text;
            //             // html += "</label>";
            //         }
            //         else //录入型
            //         {
            //             html += "巡检结果：" + pci.DefaultValue;
            //         }
            //     }
            //     html += "</div>";
            //     query.TypeDescription = html;
            //     query.Name = i + "." + query.Name;
            //     i++;
            //     lst.Add(query);
            // }

            // return Content(lst.ToJson());
            return Content("");
        }

        public ActionResult GetAttachFile(string keyValue)
        {
            var AttachFile = new AttachFileBLL().GetList(keyValue).ToList();

            return Content(AttachFile.ToJson());
        }

        public ActionResult SaveRow()
        {
            return Content("true");
        }

        #endregion


        public string GetName(int type, string ItemId)
        {
            string str = "";
            var query = deviceBLL.GetRelationDeviceItemList(1, null).ToList();
            query = query.Where(e => e.ItemId == ItemId).ToList();
            if (query.Count() <= 0)
            {
                return str;
            }
            switch (type)
            {
                case 1: //应用设备类型
                    foreach (var item in query)
                    {
                        var s = new DeviceTypeBLL().GetEntity(item.DeviceTypeId);
                        string Name = s.IsEmpty() ? "" : s.Name;
                        if (!str.Contains(Name))
                        {
                            str += Name + "|";
                        }
                    }
                    break;

                case 2://应用设备等级
                    foreach (var item in query)
                    {
                        var s = new DataItemDetailBLL().GetEntity(item.DeviceLevel);
                        string Name = s.IsEmpty() ? "" : s.ItemName;
                        if (!str.Contains(Name))
                        {
                            str += Name + "|";
                        }
                    }
                    break;

                case 3://应用项目类型
                    foreach (var item in query)
                    {
                        var s = new DataItemDetailBLL().GetEntity(item.ProjectType);
                        string Name = s.IsEmpty() ? "" : s.ItemName;
                        if (!str.Contains(Name))
                        {
                            str += Name + "|";
                        }

                    }
                    break;
                default:
                    break;
            }
            if (!str.IsEmpty())
            {
                str = str.Substring(0, str.LastIndexOf('|'));
            }

            return str;
        }
    }
}
